package cn.jxau.common.util;

import java.io.IOException;

import org.springframework.web.multipart.MultipartFile;

public class FileUploadImpl implements FileUpload {
	private static final String DEFAULT_SAVE_PATH="/";
	private String savePath;
	private MultipartFile file;
	private String fileName;//文件名
	private String fileRealPath;//文件的真实路径
	private String fileSubfix;//文件名后缀
	{
		String basePath=ProUtils.getProperty("file.save");
		if(basePath==null)
			savePath=DEFAULT_SAVE_PATH;
		else
			savePath=basePath;
	}
	public FileUploadImpl(MultipartFile file,String basePath){
		this.file=file;
		this.savePath=basePath;
		initFileUpload();
	}
	public FileUploadImpl(MultipartFile file) {
		// TODO Auto-generated constructor stub
		this.file=file;
		initFileUpload();
	}
	
	private void initFileUpload(){
		final StringBuilder build=new StringBuilder();
		String oriName=file.getOriginalFilename();//获取源文件名
		String fileType=getFileType(oriName);//获取文件类型
		this.fileName=getRandomStr()+"."+fileType;
		this.fileRealPath=savePath+"/"+fileName;
		try {
			BaseFileRelativeUtil.overrideToFile(file.getBytes(), fileRealPath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//写入文件
	}
	
	private String getRandomStr(){
		return IPTimeStamp.getIPTime();
	}
	@Override
	public String getRealFilePath() {
		// TODO Auto-generated method stub
		return this.fileRealPath;
	}

	@Override
	public String getFileName() {
		// TODO Auto-generated method stub
		return this.fileName;
	}
	
	private String getFileType(String fileName){
		String subfix=fileName.substring(fileName.lastIndexOf('.')+1);
		if(subfix==null)
			subfix="";//有些文件没有后缀
		return  subfix;
				
	}
}
